using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace ARF.Web.Controls
{
    public class ListItemXml : ListXml
    {
        private string _itemID;
        private string _itemTitle;
        private string _itemGuid;
        private string _itemUrl;

        public string ItemUrl
        {
            get { return _itemUrl; }
            set { _itemUrl = value; }
        }

        public string ItemGuid
        {
            get { return _itemGuid; }
            set { _itemGuid = value; }
        }

        public string ItemTitle
        {
            get { return _itemTitle; }
            set { _itemTitle = value; }
        }

        public string ItemID
        {
            get { return _itemID; }
            set { _itemID = value; }
        }

        protected override void BuildXml()
        {
            try
            {
                SPListItem oListItem = GetRequiredListItem();

                if (oListItem == null)
                {
                    Log.Trace("List item not found for ListItemXml control");
                    return;
                }

                XmlAsObject = Utility.Utility.CleanXml(oListItem.Xml);
            }
            catch (Exception ex)
            {
                Log.Trace(ex);
                XmlAsString = "<Error>" + ex.Message + "</Error>";
            }
        }

        protected virtual SPListItem GetRequiredListItem()
        {
            if (!string.IsNullOrEmpty(ItemGuid))
                return ContextList.GetItemByUniqueId(new Guid(ItemGuid));

            else if (!string.IsNullOrEmpty(ItemID))
                return ContextList.GetItemById(int.Parse(ItemID));

            else if (!string.IsNullOrEmpty(ItemUrl))
                return ListWeb.GetListItem(ItemUrl);

            else if (!string.IsNullOrEmpty(ItemTitle))
            {
                SPList oList = ContextList;
                SPQuery oQuery = new SPQuery(oList.DefaultView);
                oQuery.Query = string.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", ItemTitle);
                SPListItemCollection oResults = oList.GetItems(oQuery);
                if (oResults.Count > 0)
                    return oResults[0];
                else
                {
                    Log.Trace("No reults for list query with title: " + ItemTitle);
                    XmlAsString = "<Error>Item with title '" + ItemTitle + "' not found</Error>";
                    return null;
                }
            }

            Log.Trace("ListItemXml: No item specified. Please specify ItemGuid, ItemID, ItemUrl or ItemTitle");

            return null;
        }

    }
}
